import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import QtQuick3D

Rectangle {
    id: solarSystemPage
    
    // 星空背景
    gradient: Gradient {
        GradientStop { position: 0.0; color: "#000428" }
        GradientStop { position: 1.0; color: "#004e92" }
    }
    
    // 星星背景
    Repeater {
        model: 100
        Rectangle {
            x: Math.random() * solarSystemPage.width
            y: Math.random() * solarSystemPage.height
            width: Math.random() * 3
            height: width
            radius: width / 2
            color: "white"
            opacity: Math.random() * 0.8 + 0.2
            
            SequentialAnimation on opacity {
                loops: Animation.Infinite
                NumberAnimation { to: 0.2; duration: Math.random() * 2000 + 1000 }
                NumberAnimation { to: 1.0; duration: Math.random() * 2000 + 1000 }
            }
        }
    }

    // 顶部控制栏
    Rectangle {
        id: controlBar
        width: parent.width
        height: 70
        z: 10
        
        gradient: Gradient {
            GradientStop { position: 0.0; color: "#FF6B9D" }
            GradientStop { position: 1.0; color: "#FFA07A" }
        }
        
        RowLayout {
            anchors.fill: parent
            anchors.margins: 15
            spacing: 15

            Text {
                text: "🌞 太阳系探索"
                font.pixelSize: 22
                font.bold: true
                color: "white"
            }
            
            Item { Layout.fillWidth: true }
            
            // 播放/暂停按钮
            Button {
                Layout.preferredHeight: 40
                Layout.preferredWidth: 100
                font.pixelSize: 14
                font.bold: true
                
                background: Rectangle {
                    color: parent.pressed ? "#4ECDC4" : "#45B7AA"
                    radius: 20
                }
                
                contentItem: Text {
                    text: solarSystemModel.isRunning ? "⏸️ 暂停" : "▶️ 播放"
                    color: "white"
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                    font: parent.font
                }
                
                onClicked: {
                    solarSystemModel.isRunning = !solarSystemModel.isRunning
                }
            }

            // 重置按钮
            Button {
                Layout.preferredHeight: 40
                Layout.preferredWidth: 100
                font.pixelSize: 14
                font.bold: true
                
                background: Rectangle {
                    color: parent.pressed ? "#FF6B6B" : "#FF8E8E"
                    radius: 20
                }
                
                contentItem: Text {
                    text: "🔄 重置"
                    color: "white"
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                    font: parent.font
                }
                
                onClicked: {
                    solarSystemModel.resetToCurrentTime()
                }
            }

            // 速度滑块
            Text {
                text: "速度:"
                color: "white"
                font.pixelSize: 14
                font.bold: true
            }
            
            Slider {
                id: speedSlider
                Layout.preferredWidth: 180
                from: 1
                to: 200
                value: 50
                stepSize: 1
                
                onValueChanged: {
                    solarSystemModel.timeSpeed = value
                }
                
                Component.onCompleted: {
                    solarSystemModel.timeSpeed = value
                }
            }
            
            Text {
                text: {
                    var daysPerSec = (speedSlider.value / 10).toFixed(1);
                    return daysPerSec + " 天/秒";
                }
                color: "white"
                font.pixelSize: 14
                font.bold: true
                Layout.preferredWidth: 80
            }
            
            // NASA 官网按钮
            Button {
                Layout.preferredHeight: 40
                Layout.preferredWidth: 140
                font.pixelSize: 13
                font.bold: true
                
                background: Rectangle {
                    color: parent.pressed ? "#9B59B6" : "#8E44AD"
                    radius: 20
                    border.color: "#ECF0F1"
                    border.width: 2
                }
                
                contentItem: Text {
                    text: "🚀 NASA官网"
                    color: "white"
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                    font: parent.font
                }
                
                onClicked: {
                    Qt.openUrlExternally("https://eyes.nasa.gov/apps/solar-system/#/home")
                }
            }
        }
    }

    // 太阳系动画区域
    Item {
        id: solarSystem
        anchors.top: controlBar.bottom
        anchors.bottom: parent.bottom
        anchors.left: parent.left
        anchors.right: parent.right
        
        property real centerX: width / 2 + offsetX
        property real centerY: height / 2 + offsetY
        property real scale: Math.min(width, height) / 1000
        property real zoomLevel: 1.0  // 缩放级别
        property real offsetX: 0  // X偏移
        property real offsetY: 0  // Y偏移
        
        // 鼠标交互：滚轮缩放 + 左键拖动
        MouseArea {
            anchors.fill: parent
            acceptedButtons: Qt.LeftButton
            
            property real lastX: 0
            property real lastY: 0
            property bool isDragging: false
            
            onWheel: function(wheel) {
                var delta = wheel.angleDelta.y / 120
                var zoomFactor = delta > 0 ? 1.1 : 0.9
                var newZoom = solarSystem.zoomLevel * zoomFactor
                
                // 限制缩放范围
                if (newZoom >= 0.3 && newZoom <= 5.0) {
                    solarSystem.zoomLevel = newZoom
                }
                
                wheel.accepted = true
            }
            
            onPressed: function(mouse) {
                lastX = mouse.x
                lastY = mouse.y
                isDragging = true
                cursorShape = Qt.ClosedHandCursor
            }
            
            onReleased: function(mouse) {
                isDragging = false
                cursorShape = Qt.OpenHandCursor
            }
            
            onPositionChanged: function(mouse) {
                if (isDragging) {
                    var dx = mouse.x - lastX
                    var dy = mouse.y - lastY
                    solarSystem.offsetX += dx
                    solarSystem.offsetY += dy
                    lastX = mouse.x
                    lastY = mouse.y
                }
            }
            
            cursorShape: Qt.OpenHandCursor
        }
        
        // 太阳
        Rectangle {
            id: sun
            x: parent.centerX - width / 2
            y: parent.centerY - height / 2
            width: 80 * parent.scale * parent.zoomLevel
            height: 80 * parent.scale * parent.zoomLevel
            radius: width / 2
            
            gradient: Gradient {
                GradientStop { position: 0.0; color: "#FDB813" }
                GradientStop { position: 1.0; color: "#FF6B35" }
            }
            
            // 太阳光晕
            Rectangle {
                anchors.centerIn: parent
                width: parent.width * 1.3
                height: parent.height * 1.3
                radius: width / 2
                color: "#FFA50050"
                z: -1
                
                SequentialAnimation on scale {
                    loops: Animation.Infinite
                    NumberAnimation { to: 1.2; duration: 1500; easing.type: Easing.InOutQuad }
                    NumberAnimation { to: 1.0; duration: 1500; easing.type: Easing.InOutQuad }
                }
            }
            
            Text {
                anchors.centerIn: parent
                text: "☀️"
                font.pixelSize: parent.width * 0.6
            }
        }
        
        // 行星轨道和行星
            Repeater {
                model: solarSystemModel
                
                Item {
                    id: planetOrbit
                    anchors.fill: parent
                    
                    property real orbitRadius: model.distance * 80 * solarSystem.scale * solarSystem.zoomLevel
                    property real angle: model.currentAngle || 0
                    property real planetSize: (15 + model.radius * 8) * solarSystem.scale * solarSystem.zoomLevel  // 增大行星
                    property var planetColorVec: model.color || Qt.vector3d(0.8, 0.8, 0.8)
                    property color planetColor: Qt.rgba(planetColorVec.x, planetColorVec.y, planetColorVec.z, 1.0)
                
                // 轨道
                Rectangle {
                    x: solarSystem.centerX - width / 2
                    y: solarSystem.centerY - height / 2
                    width: planetOrbit.orbitRadius * 2
                    height: planetOrbit.orbitRadius * 2
                    radius: width / 2
                    color: "transparent"
                    border.color: "#FFFFFF30"
                    border.width: 1
                }
                
                // 行星
                Item {
                    id: planet
                    x: solarSystem.centerX + planetOrbit.orbitRadius * Math.cos(planetOrbit.angle * Math.PI / 180) - width / 2
                    y: solarSystem.centerY + planetOrbit.orbitRadius * Math.sin(planetOrbit.angle * Math.PI / 180) - height / 2
                    width: planetOrbit.planetSize
                    height: planetOrbit.planetSize
                    
                    // 平滑的位置动画
                    Behavior on x {
                        enabled: solarSystemModel.isRunning
                        SmoothedAnimation { velocity: -1; duration: 50 }
                    }
                    Behavior on y {
                        enabled: solarSystemModel.isRunning
                        SmoothedAnimation { velocity: -1; duration: 50 }
                    }
                    
                    // 悬停放大效果
                    scale: planetMouse.containsMouse ? 1.3 : 1.0
                    Behavior on scale {
                        NumberAnimation { duration: 200 }
                    }
                    
                    // 行星主体
                    Rectangle {
                        id: planetBody
                        anchors.fill: parent
                        radius: width / 2
                        
                        // 根据行星类型使用不同的渐变
                        gradient: Gradient {
                            GradientStop { 
                                position: 0.0
                                color: Qt.lighter(planetOrbit.planetColor, 1.3)
                            }
                            GradientStop { 
                                position: 0.5
                                color: planetOrbit.planetColor
                            }
                            GradientStop { 
                                position: 1.0
                                color: Qt.darker(planetOrbit.planetColor, 1.5)
                            }
                        }
                        
                        border.color: Qt.lighter(planetOrbit.planetColor, 1.5)
                        border.width: 2
                        
                        // 自转动画
                        rotation: model.rotationAngle || 0
                        Behavior on rotation {
                            enabled: solarSystemModel.isRunning
                            RotationAnimation { 
                                direction: RotationAnimation.Shortest
                                duration: 50
                            }
                        }
                        
                        // 地球特效：陆地纹理（使用Canvas绘制真实轮廓）
                        Canvas {
                            visible: index === 2
                        anchors.fill: parent
                            contextType: "2d"
                            
                            onPaint: {
                                var ctx = getContext("2d")
                                ctx.clearRect(0, 0, width, height)
                                
                                ctx.fillStyle = "#228B22"
                                ctx.globalAlpha = 0.85
                                
                                var w = width
                                var h = height
                                
                                // 亚洲大陆（简化轮廓）
                                ctx.beginPath()
                                ctx.moveTo(w * 0.65, h * 0.25)
                                ctx.lineTo(w * 0.75, h * 0.3)
                                ctx.lineTo(w * 0.8, h * 0.4)
                                ctx.lineTo(w * 0.85, h * 0.45)
                                ctx.lineTo(w * 0.8, h * 0.55)
                                ctx.lineTo(w * 0.7, h * 0.6)
                                ctx.lineTo(w * 0.6, h * 0.55)
                                ctx.lineTo(w * 0.55, h * 0.4)
                                ctx.lineTo(w * 0.6, h * 0.3)
                                ctx.closePath()
                                ctx.fill()
                                
                                // 欧洲
                                ctx.beginPath()
                                ctx.moveTo(w * 0.48, h * 0.2)
                                ctx.lineTo(w * 0.55, h * 0.25)
                                ctx.lineTo(w * 0.52, h * 0.35)
                                ctx.lineTo(w * 0.45, h * 0.38)
                                ctx.lineTo(w * 0.42, h * 0.28)
                                ctx.closePath()
                                ctx.fill()
                                
                                // 非洲
                                ctx.fillStyle = "#2E7D32"
                                ctx.beginPath()
                                ctx.moveTo(w * 0.45, h * 0.4)
                                ctx.lineTo(w * 0.52, h * 0.42)
                                ctx.lineTo(w * 0.55, h * 0.5)
                                ctx.lineTo(w * 0.53, h * 0.65)
                                ctx.lineTo(w * 0.48, h * 0.68)
                                ctx.lineTo(w * 0.43, h * 0.62)
                                ctx.lineTo(w * 0.4, h * 0.5)
                                ctx.closePath()
                                ctx.fill()
                                
                                // 北美洲
                                ctx.fillStyle = "#388E3C"
                                ctx.beginPath()
                                ctx.moveTo(w * 0.15, h * 0.18)
                                ctx.lineTo(w * 0.28, h * 0.22)
                                ctx.lineTo(w * 0.32, h * 0.3)
                                ctx.lineTo(w * 0.3, h * 0.42)
                                ctx.lineTo(w * 0.25, h * 0.48)
                                ctx.lineTo(w * 0.18, h * 0.45)
                                ctx.lineTo(w * 0.12, h * 0.35)
                                ctx.lineTo(w * 0.1, h * 0.25)
                                ctx.closePath()
                                ctx.fill()
                                
                                // 南美洲
                                ctx.beginPath()
                                ctx.moveTo(w * 0.25, h * 0.5)
                                ctx.lineTo(w * 0.3, h * 0.52)
                                ctx.lineTo(w * 0.32, h * 0.65)
                                ctx.lineTo(w * 0.28, h * 0.75)
                                ctx.lineTo(w * 0.22, h * 0.72)
                                ctx.lineTo(w * 0.2, h * 0.6)
                                ctx.closePath()
                                ctx.fill()
                                
                                // 澳大利亚
                                ctx.fillStyle = "#43A047"
                                ctx.beginPath()
                                ctx.ellipse(w * 0.78, h * 0.68, w * 0.08, h * 0.06, 0, 0, Math.PI * 2)
                                ctx.fill()
                            }
                            
                            Component.onCompleted: {
                                requestPaint()
                            }
                        }
                        
                        // 地球特效：晨昏线（更明显）
                        Rectangle {
                            visible: index === 2  // 仅地球显示
                            anchors.left: parent.horizontalCenter
                            anchors.top: parent.top
                            anchors.bottom: parent.bottom
                            width: parent.width / 2
                            radius: parent.radius
                            
                            gradient: Gradient {
                                orientation: Gradient.Horizontal
                                GradientStop { position: 0.0; color: "#00000000" }
                                GradientStop { position: 0.2; color: "#00000050" }
                                GradientStop { position: 0.5; color: "#000000A0" }
                                GradientStop { position: 1.0; color: "#000000D0" }
                            }
                        }
                        
                        // 行星表面纹理（简化的斑点）
                        Repeater {
                            model: index === 4 ? 3 : (index === 5 ? 2 : 0)  // 木星3个斑点，土星2个
                            Rectangle {
                                x: parent.width * (0.2 + modelData * 0.3)
                                y: parent.height * 0.5
                                width: parent.width * 0.3
                                height: parent.height * 0.15
                                radius: height / 2
                                color: Qt.darker(planetOrbit.planetColor, 1.2)
                                opacity: 0.5
                            }
                        }
                    }
                    
                    // 土星光环（在行星后面）
                    Rectangle {
                        visible: index === 5  // 土星
                        anchors.centerIn: parent
                        width: parent.width * 2.2
                        height: parent.height * 0.3
                        radius: width / 2
                        color: "transparent"
                        border.color: Qt.rgba(0.95, 0.85, 0.65, 0.6)
                        border.width: parent.width * 0.15
                        z: -1
                        rotation: 15  // 倾斜角度
                    }
                    
                    // 月球（仅地球）
                    Rectangle {
                        visible: index === 2
                        id: moon
                        width: parent.width * 0.27
                        height: width
                        radius: width / 2
                        
                        // 月球轨道动画 - 使用独立的公转周期27.3天
                        // 月球公转速度应该是地球公转的365.25/27.3 ≈ 13.37倍
                        property real moonAngle: (model.currentAngle || 0) * 13.37
                        property real moonDistance: parent.width * 0.8
                        
                        x: parent.width / 2 + moonDistance * Math.cos(moonAngle * Math.PI / 180) - width / 2
                        y: parent.height / 2 + moonDistance * Math.sin(moonAngle * Math.PI / 180) - height / 2
                        
                        gradient: Gradient {
                            GradientStop { position: 0.0; color: "#E0E0E0" }
                            GradientStop { position: 1.0; color: "#808080" }
                        }
                        
                        border.color: "#C0C0C0"
                        border.width: 2
                        
                        // 月球陨石坑
                        Repeater {
                            model: 3
                            Rectangle {
                                x: moon.width * (0.2 + modelData * 0.25)
                                y: moon.height * (0.3 + modelData * 0.2)
                                width: moon.width * 0.15
                                height: width
                                radius: width / 2
                                color: "#60606040"
                            }
                        }
                    }
                    
                    // 行星名称
                    Text {
                        anchors.top: parent.bottom
                        anchors.topMargin: 5
                        anchors.horizontalCenter: parent.horizontalCenter
                        text: model.chineseName || model.name
                        color: "white"
                        font.pixelSize: 12
                        font.bold: true
                        
                        // 文字阴影
                        style: Text.Outline
                        styleColor: "#000000"
                    }
                    
                    MouseArea {
                        id: planetMouse
                        anchors.fill: parent
                        hoverEnabled: true
                        cursorShape: Qt.PointingHandCursor
                        acceptedButtons: Qt.LeftButton | Qt.RightButton
                        
                        onClicked: function(mouse) {
                            if (mouse.button === Qt.LeftButton) {
                                if (index === 2) {  // 地球：单击打开3D详细视图
                                    earth3DLoader.active = true
                                } else {  // 其他行星：打开简单信息对话框
                            planetInfoDialog.planetIndex = index
                            planetInfoDialog.open()
                                }
                            }
                        }
                    }
                }
            }
        }
    }
    
    // 行星信息对话框
    Dialog {
        id: planetInfoDialog
        property int planetIndex: 0
        
        title: "🪐 行星信息"
        anchors.centerIn: parent
        width: 400
        height: 400
        modal: true
        
        background: Rectangle {
            color: "#1a1a2e"
            radius: 15
            border.color: "#FFD700"
            border.width: 2
        }
        
        contentItem: Column {
            spacing: 20
            padding: 20
            
            // 行星名称
            Text {
                text: planetInfoDialog.planetIndex >= 0 && planetInfoDialog.planetIndex < solarSystemModel.rowCount() ? 
                      solarSystemModel.get(planetInfoDialog.planetIndex).chineseName : ""
                font.pixelSize: 28
                font.bold: true
                color: "#FFD700"
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            // 行星图标
            Text {
                text: "🪐"
                font.pixelSize: 60
                anchors.horizontalCenter: parent.horizontalCenter
            }
            
            // 行星信息
            Column {
                width: parent.width
                spacing: 12
                
                Row {
                    spacing: 10
            Text {
                        text: "英文名:"
                        color: "#AAAAAA"
                font.pixelSize: 16
                        width: 100
                    }
                    Text {
                        text: planetInfoDialog.planetIndex >= 0 && planetInfoDialog.planetIndex < solarSystemModel.rowCount() ? 
                              solarSystemModel.get(planetInfoDialog.planetIndex).name : ""
                color: "white"
                        font.pixelSize: 16
                        font.bold: true
                    }
            }
            
                Row {
                    spacing: 10
            Text {
                        text: "半径:"
                        color: "#AAAAAA"
                font.pixelSize: 16
                        width: 100
                    }
                    Text {
                        text: planetInfoDialog.planetIndex >= 0 && planetInfoDialog.planetIndex < solarSystemModel.rowCount() ? 
                              solarSystemModel.get(planetInfoDialog.planetIndex).radius.toFixed(2) + " 地球半径" : ""
                color: "white"
                        font.pixelSize: 16
                    }
            }
            
                Row {
                    spacing: 10
            Text {
                        text: "距离:"
                        color: "#AAAAAA"
                font.pixelSize: 16
                        width: 100
                    }
                    Text {
                        text: planetInfoDialog.planetIndex >= 0 && planetInfoDialog.planetIndex < solarSystemModel.rowCount() ? 
                              solarSystemModel.get(planetInfoDialog.planetIndex).distance.toFixed(2) + " 天文单位" : ""
                color: "white"
                        font.pixelSize: 16
                    }
            }
            
                Row {
                    spacing: 10
            Text {
                        text: "公转周期:"
                        color: "#AAAAAA"
                font.pixelSize: 16
                        width: 100
                    }
            Text {
                        text: planetInfoDialog.planetIndex >= 0 && planetInfoDialog.planetIndex < solarSystemModel.rowCount() ? 
                              solarSystemModel.get(planetInfoDialog.planetIndex).orbitalPeriod.toFixed(0) + " 地球日" : ""
                color: "white"
                font.pixelSize: 16
                    }
                }
            }
            
            // 关闭按钮
            Button {
                text: "关闭"
                anchors.horizontalCenter: parent.horizontalCenter
                
                background: Rectangle {
                    color: parent.pressed ? "#FF6B6B" : "#FF8E8E"
                    radius: 20
                }
                
                contentItem: Text {
                    text: parent.text
                    color: "white"
                    horizontalAlignment: Text.AlignHCenter
                    verticalAlignment: Text.AlignVCenter
                    font.pixelSize: 14
                    font.bold: true
                }
                
                onClicked: planetInfoDialog.close()
            }
        }
    }
    
    // 3D地球详情视图（使用Loader延迟加载）
    Loader {
        id: earth3DLoader
        anchors.fill: parent
        active: false
        z: 100
        source: active ? "EarthDetail3D.qml" : ""
        
        onLoaded: {
            console.log("EarthDetail3D 已加载")
            if (item) {
                item.closeRequested.connect(function() {
                    earth3DLoader.active = false
                })
            }
        }
        
        onStatusChanged: {
            console.log("Loader status:", status, "(0=Null, 1=Ready, 2=Loading, 3=Error)")
        }
    }
}